# Copyright (C) 2009 Israel Herraiz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Authors : Israel Herraiz <isra@herraiz.org>

"""
@author:       Israel Herraiz
@license:      GNU GPL version 3 or any later version
@contact:      isra@herraiz.org
"""

import os
import sys
from commands import getoutput

class Application:

    def __init__(self, command, brightness):

        self.__config_fn = None
        self.__config_fn = self.__getConfigFilename()
        self.__brightness = int(brightness)
        self.__command = command

    def run(self):

        if 'inc' == self.__command:
            self.run_inc()
        elif 'dec'== self.__command:
            self.__brightness = -self.__brightness
            self.run_inc()
        elif 'set'== self.__command:
            self.run_set()
        elif 'get' == self.__command:
            self.run_get()

    def run_inc(self): 

        s = self.__readBrightness()
        
        # Increases or decreases brightness
        s =  s + self.__percentToBrightness(self.__brightness)
        
        if s > 255:
            s = 255

        if s < 2:
            s = 2

        cmd = "xrandr --output LVDS " \
                    " --set BACKLIGHT %d" \
                    " --set BACKLIGHT_CONTROL legacy" \
                    " --output VGA --auto" % s
        
        os.system(cmd)
        self.__writeBrightness(s)

    def run_get(self):
        s = self.__readBrightness()
        percent = self.__brightnessToPercent(s)
        print("Brightness is %d %%" % percent)


    def run_set(self):
        if self.__brightness < 0 or self.__brightness > 100:
            print("Invalid value for brightness. It must be between 0% and 100%")
            sys.exit(1)

        s = self.__percentToBrightness(self.__brightness)
        
        cmd = "xrandr --output LVDS " \
                    " --set BACKLIGHT %d" \
                    " --set BACKLIGHT_CONTROL legacy" \
                    " --output VGA --auto" % s
        
        os.system(cmd)

        self.__writeBrightness(s)

    def __readBrightness(self):
        if os.path.exists(self.__config_fn):
            # Read last value
            f = open(self.__config_fn,'r')
            s = int(f.readline())
            f.close()
        else:
            s = self.__readBrightnessFromSystem()

        return s

    def __writeBrightness(self,s):
        f = open(self.__config_fn,'w')
        f.write(str(s))
        f.close()

        
    def __readBrightnessFromSystem(self):

        cmd = "xrandr --prop " \
            "| grep 'BACKLIGHT:' "\
            "| awk -F ':' '{print $2}' "\
            "| awk -F '(' '{print $1}'"

        s = int(getoutput(cmd))
        return s
    
    def __brightnessToPercent(self,brightness):

        # Minimum bright is 2, maximum is 255
        percent = (brightness-2.0)/253.0*100.0

        return percent

    def __percentToBrightness(self,percent):

        # Minimum bright is 2, maximum is 255
        brightness = percent*253.0/100.0+2.0

        return int(brightness)

    def __getConfigFilename(self):

        if not self.__config_fn:
            mydir = os.path.expanduser("~")
            mydir = os.path.join(mydir,".x360")
            if not os.path.exists(mydir):
                os.mkdir(mydir)

            self.__config_fn = os.path.join(mydir,"brightness")
                                
        return self.__config_fn
